<?php
// +----------------------------------------------------------------------
//            -------------------------
//           /   / ----------------\  \
//          /   /             \  \
//         /   /              /  /
//        /   /    /-------------- /  /
//       /   /    /-------------------\  \
//      /   /                   \  \
//     /   /                     \  \
//    /   /                      /  /
//   /   /      /----------------------- /  /
//  /-----/      /---------------------------/
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://baimifan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Sage 2016/4/19  14:05
// +----------------------------------------------------------------------
namespace Wechat\Controller;
use Common\Model\PayModel;
require_once COMMON_PATH . 'WxpayAPI/example/WxPay.JsApiPay.php';

Class OrderController extends BaseController {
    /*查询所有订单*/
    function all() {
        $this->display();
    }

    //产生新的活动订单并返回pay_id交由支付中心处理
    function bear_order_activity() {
        $activity_id = I("post.id");
        //产生新的订单，在order模型中统一插入
        $Order = D("Order");
        $user_id = session("user_id");
        //生成订单
        $res = $Order->bear_order_activity($user_id, $activity_id);  //得到，默认当前用户
        echo json_encode($res);
    }

    //统一下单-活动-获取参数
    function getJsApiParameters_activity() {
        //①、获取用户openid
        $pay_id = I("post.id");
        $user_id = session("user_id");
        //下单前检查是否满足支付条件
        //是否已支付，是否报名结束，是否报名满员
        $rcode = ["status" => "error", "message" => ""];

        $Order = D("Order");
        $is_pay = $Order->is_pay($pay_id);
        if ($is_pay) {
            $rcode = ["status" => "error", "message" => "不能重复报名"];//已报名成功，或退款过
            echo json_encode($rcode);
            exit();
        }
        $Apply = M("Activity_apply");
        $map["user_id"] = $user_id;
        $map["pay_id"] = $pay_id;
        $dapp = $Apply->where($map)->find();
        $activity_id = $dapp["activity_id"];
        $Activity = M("Activity");
        $da = $Activity->where(['activity_id'=>$activity_id])->find();
        if (strtotime($da['apply_end']) < time()) {
            $rcode = ["status" => "error", "message" => "报名时间已过"];
            echo json_encode($rcode);
            exit();
        }
        if ($da['apply_num'] <= 0) {
            $rcode = ["status" => "error", "message" => "报名人数已满"];
            echo json_encode($rcode);
            exit();
        }
        //是否免报名费次数足够
        if ($dapp["is_applyfree"] == "1") {
            //免运费情况下，检查可免运费次数
            $Card = M("Card");
            $dc = $Card->where(['user_id'=>$user_id])->find();
            if (strtotime($dc['expire_time']) < time() || strtotime($dc['create_time']) > time()) {
                $rcode = ["status" => "error", "message" => "会员已过期或已延期，请续费或延期时间内操作"];
                echo json_encode($rcode);
                exit();
            }
            if ($dc['num_activity'] < $da['num_deduct']) {
                $rcode = ["status" => "error", "message" => "可免报名费次数不足，请充值或重新前往报名"];
                echo json_encode($rcode);
                exit();
            }
        }
//        $rcode = ["status" => "success", "message" => "可以报名"];
        //echo json_encode($rcode,JSON_UNESCAPED_UNICODE);
        //exit();
        $Wechat = M("Wechat");
        $tools = new \JsApiPay();
        $duser = $Wechat->where("user_id=$user_id")->field("openid")->find();
        $openId = $duser['openid'];
        $Pay = M("Pay");
        $dp = $Pay->where("pay_id=$pay_id")->field("money")->find();
        $attach = array('pay_id' => $pay_id, 'money' => $dp['money']);
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("活动报名");
        $input->SetAttach(json_encode($attach));  //订单业务信息
        $input->SetOut_trade_no(\WxPayConfig::MCHID  . $pay_id);
        $input->SetTotal_fee($dp['money']*100);  //单位：分
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetNotify_url(C("WECHAT_NOTIFY_BASEURL") . "Pay/notify_activity");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
        //printf_info($order);
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $rcode = ["status" => "success", "message" => $jsApiParameters];
        echo json_encode($rcode);
    }

    //产生新的借书订单并返回的是pay_id
    function bear_order_rent() {
        $liststr = I("post.liststr");
        $list = bookinfo_strtoarr($liststr);
        $remark=I("post.remark");

        $is_ffree = I("post.is_ffree");
        $User = D("User");
        $address = $User->getAddress();
        $Order = D("Order");
        $user_id = session("user_id");
        $pay_id = $Order->bear_order_book_rent($user_id, 1, $address, $is_ffree, $list,$remark);
        if($pay_id){
            $j=[
                'status'=>'success',
                'data'=>$pay_id
            ];
            echo json_encode($j);
            return;
        }else{
            $j=[
                'status'=>'error',
                'data'=>'系统错误'
            ];
            echo json_encode($j);
            return;
        }
    }

    //统一下单-借阅-获取参数
    function getJsApiParameters_rent() {
        //$pay_id=52;
        $pay_id = I("post.id");
        $user_id = session("user_id");
        //下单前检查是否满足支付条件
        //是否已支付，是否借阅库存不足,
        $rcode = ["status" => "error", "message" => ""];
        $Order = D("Order");
        //订单是否存在
        $is_exist = $Order->is_exist($pay_id); //返回1：存在
        if ($is_exist == 0) {
            $rcode = ["status" => "error", "message" => "此订单不存在"];
            echo json_encode($rcode, JSON_UNESCAPED_UNICODE);
            exit();
        }
        //订单是否已取消
        $is_cancel = $Order->is_cancel($pay_id);
        if ($is_cancel) {
            $rcode = ["status" => "error", "message" => "此订单已取消，无法操作"];
            echo json_encode($rcode, JSON_UNESCAPED_UNICODE);
            exit();
        }
        //订单是否已支付
        $is_pay = $Order->is_pay($pay_id);
        if ($is_pay) {
            $rcode = ["status" => "error", "message" => "已报名成功，不能重复报名"];
            echo json_encode($rcode, JSON_UNESCAPED_UNICODE);
            exit();
        }
        $Order = M("Order_book");
        $dorder = $Order->where("pay_id=$pay_id AND user_id=$user_id")->find();
        $order_id = $dorder['order_id'];
        $Order_has_book = M("View_order_has_book");
        $dbook = $Order_has_book->where("order_id=$order_id")->select();
        foreach ($dbook as $k => $v) {
            if ($v['is_del'] == 1) {
                $rcode = ["status" => "error", "message" => "订单图书已删除"];
                echo json_encode($rcode, JSON_UNESCAPED_UNICODE);
                exit();
            }
            if ($v['stock_rent'] < $v['quantity']) {
                $rcode = ["status" => "error", "message" => $v['sm'].",此书借阅库存不足,"];
                echo json_encode($rcode, JSON_UNESCAPED_UNICODE);
                exit();
            }
        }
        //是否免运费次数足够
        if ($dorder["is_freightfree"] == "1") {
            //免运费情况下，检查可免运费次数
            $Card = M("Card");
            $dc = $Card->where("user_id=$user_id")->find();
            if (strtotime($dc['expire_time']) < time() || strtotime($dc['create_time']) > time()) {
                $rcode = ["status" => "error", "message" => "会员已过期或已延期，请续费或延期时间内操作"];
                echo json_encode($rcode, JSON_UNESCAPED_UNICODE);
                exit();
            }
            if ($dc['num_delivery'] <= 0) {
                $rcode = ["status" => "error", "message" => "可免借阅运费不足，请充值或重新借阅"];
                echo json_encode($rcode, JSON_UNESCAPED_UNICODE);
                exit();
            }
        }
        $Wechat = M("Wechat");
        $tools = new \JsApiPay();
        $duser = $Wechat->where("user_id=$user_id")->field("openid")->find();
        $openId = $duser['openid'];
        $Pay = M("Pay");
        $dp = $Pay->where("pay_id=$pay_id")->field("money")->field("money")->find();
        $attach = array('pay_id' => $pay_id, 'money' => $dp['money']);
        if($dp['money']==0){
            $Pay=new PayModel();
            if($Pay->complete_rent($pay_id,$dp['money'])) {
                $rcode = ["status" => "complete", "message" =>'借阅成功'];
            }else{
                $rcode = ["status" => "error", "message" => "系统错误,借阅失败"];
            }
            echo json_encode($rcode, JSON_UNESCAPED_UNICODE);
            exit();
        }
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("借阅订单");
        $input->SetAttach(json_encode($attach));
        $input->SetOut_trade_no(\WxPayConfig::MCHID . $pay_id);
        $input->SetTotal_fee($dp['money']*100);  //单位：分
//        $input->SetTotal_fee(1);  //单位：分
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url(C("WECHAT_NOTIFY_BASEURL") . 'Pay/notify_rent');
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
        //printf_info($order);
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $rcode = ["status" => "success", "message" => $jsApiParameters];
        echo json_encode($rcode);
    }

    //产生新的购书订单并返回pay_id
    function bear_order_buy() {
        $liststr = I("post.liststr");
        $list = bookinfo_strtoarr($liststr);
        $remark=I("post.remark");
        //检查库存
        foreach($list as $k=>$v){
            //echo $v['book_id'].$v['num'];
            $map["book_id"]=$v['book_id'];
            $d=M('book')->where($map)->find();
            if(!$d){
                $j=[
                    'status'=>'error',
                    'data'=>'此书不存在'
                ];
                echo json_encode($j);
                return;
            }
            if ($d['stock_buy'] < $v['num']) {
                $j=[
                    'status'=>'error',
                    'data'=>$d['sm'].",此书库存不足"
                ];
                echo json_encode($j);
                return;
            }
        }
        $User = D("User");
        $address = $User->getAddress();
        $Order = D("Order");
        $user_id = session("user_id");
        $pay_id = $Order->bear_order_book_buy($user_id, 0, $address, $list,$remark);
        if($pay_id){
            $j=[
                'status'=>'success',
                'data'=>$pay_id
            ];
            echo json_encode($j);
            return;
        }else{
            $j=[
                'status'=>'error',
                'data'=>'系统错误'
            ];
            echo json_encode($j);
            return;
        }
    }

    //统一下单-购书-获取参数
    function getJsApiParameters_buy() {
        //①、获取用户openid
        //$pay_id=52;
        $pay_id = I("post.id");
        $user_id = session("user_id");
        //下单前检查是否满足支付条件
        //是否已支付，是否借阅库存不足
        $rcode = ["status" => "error", "message" => ""];
        $Order = D("Order");
        //订单是否存在
        $is_exist = $Order->is_exist($pay_id); //返回1：存在
        if ($is_exist == 0) {
            $rcode = ["status" => "error", "message" => "此订单不存在"];
            echo json_encode($rcode, JSON_UNESCAPED_UNICODE);
            exit();
        }
        //订单是否已取消
        $is_cancel = $Order->is_cancel($pay_id);
        if ($is_cancel) {
            $rcode = ["status" => "error", "message" => "此订单已取消，无法操作"];
            echo json_encode($rcode, JSON_UNESCAPED_UNICODE);
            exit();
        }
        //订单是否已支付
        $is_pay = $Order->is_pay($pay_id);
        if ($is_pay) {
            $rcode = ["status" => "error", "message" => "已报名成功，不能重复报名"];
            echo json_encode($rcode, JSON_UNESCAPED_UNICODE);
            exit();
        }
        $Order = M("Order_book");
        $dorder = $Order->where("pay_id=$pay_id AND user_id=$user_id")->find();
        $order_id = $dorder['order_id'];
        $Order_has_book = M("View_order_has_book");
        $dbook = $Order_has_book->where("order_id=$order_id")->select();
        foreach ($dbook as $k => $v) {
            if ($v['is_del'] == 1) {
                $rcode = ["status" => "error", "message" => "订单图书已删除"];
                echo json_encode($rcode, JSON_UNESCAPED_UNICODE);
                exit();
            }
            if ($v['stock_buy'] < $v['quantity']) {
                $rcode = ["status" => "error", "message" => "图书库存不足"];
                echo json_encode($rcode, JSON_UNESCAPED_UNICODE);
                exit();
            }
        }
        $Wechat = M("Wechat");
        $tools = new \JsApiPay();
        $duser = $Wechat->where("user_id=$user_id")->field("openid")->find();
        $openId = $duser['openid'];
        $Pay = M("Pay");
        $dp = $Pay->where("pay_id=$pay_id")->field("money")->find();
        $attach = array('pay_id' => $pay_id, 'money' => $dp['money']);
        if($dp['money']==0){
            $Pay=new PayModel();
            if($Pay->complete_buy($pay_id,$dp['money'])) {
                $rcode = ["status" => "complete", "message" =>'支付成功'];
            }else{
                $rcode = ["status" => "error", "message" => "系统错误,完成失败"];
            }
            echo json_encode($rcode, JSON_UNESCAPED_UNICODE);
            exit();
        }
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("购书");
        $input->SetAttach(json_encode($attach));
        $input->SetOut_trade_no(\WxPayConfig::MCHID . $pay_id);
        $input->SetTotal_fee($dp['money']*100);  //单位：分
//        $input->SetTotal_fee(1);  //单位：分 测试
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url(C("WECHAT_NOTIFY_BASEURL") . "Pay/notify_buy");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $rcode = ["status" => "success", "message" => $jsApiParameters];
        echo json_encode($rcode);
    }

    //生成会员充值订单,返回pay_id
    function bear_order_vip() {
        $type_id = I("post.id");
        $Order = D("Order");
        $user_id = session("user_id");
        //生成订单
        $pay_id = $Order->bear_order_vip($user_id, $type_id);  //得到，默认当前用户
        echo $pay_id;
    }

    //统一下单-VIP-获取参数
    function getJsApiParameters_vip() {
        //①、获取用户openid
        $pay_id = I("post.id");
        $user_id = session("user_id");
        $Wechat = M("Wechat");
        $tools = new \JsApiPay();
        $duser = $Wechat->where("user_id=$user_id")->field("openid")->find();
        $openId = $duser['openid'];
        $Pay = M("Pay");
        $dp = $Pay->where("pay_id=$pay_id")->field("money")->find();
        $attach = array('pay_id' => $pay_id, 'money' => $dp['money']);
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("会员卡充值");
        $input->SetAttach(json_encode($attach));
        $input->SetOut_trade_no(\WxPayConfig::MCHID . $pay_id);
        $input->SetTotal_fee($dp['money']*100);  //单位：分
//        $input->SetTotal_fee(1);  //单位：分 测试
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url(C("WECHAT_NOTIFY_BASEURL") . "Pay/notify_vip");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
        //printf_info($order);
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $rcode = ["status" => "success", "message" => $jsApiParameters];
        echo json_encode($rcode);
    }

    //订单-确认收货
    function confirmreceive() {
        $order_id = I("get.id");
        $Order = M("Order_book");
        $map['user_id'] = session("user_id");
        $map['order_id'] = $order_id;
        $map['state_order'] = 2;
        $data['state_order'] = 3;
        $Order->where($map)->save($data);
        //通知消息
        $Message = D("Message");
        $user_id = session("user_id");
        $msg = "【新华书店】您的订单：{$order_id}（订单号）已签收，评价已阅书籍可换取积分哦~";
        $Message->sendmessage($user_id, $msg);
        $map['state_order'] = 3;
        $d = $Order->where($map)->field("type")->find();
        if ($d['type']) {
            //借阅订单页面
            $this->redirect("User/order_rent");
        } else {
            $this->redirect("User/order_buy");
        }
    }

    //订单-取消订单
    function cancelorder() {
        $pay_id = I("get.id");
        $Pay = M("Pay");
        $Pay->startTrans();
        $Pay->where("pay_id=$pay_id  AND type in (1,2)")->data("status=-1")->save();
        $d = $Pay->where("pay_id=$pay_id")->field("status,type")->find();
        if ($d['status'] == -1) {
            $Pay->commit();
        } else {
            $Pay->rollback();
        }
        if ($d['type'] == 1) {
            $this->redirect("User/order_rent");
        }
        switch ($d['type']) {
            case 1:
                $this->redirect("User/order_rent");
                break;
            case 2:
                $this->redirect("User/order_buy");
                break;
            default:
                $this->redirect("User/index");
                break;
        }
    }

    //订单-查看物流
    function express() {
        $order_id = I("get.id");
        $Express = M("Order_delivery");
        $d = $Express->where("order_id=$order_id")->find();
        $list = array();
        $list['phone'] = 95311;
        if (is_null($d)) {
            $list['state'] = "未出货";
            $list['source'] = "暂无";
            $list['order_num'] = "无";
            $list['record'] = [];
            $this->assign("d", $list);
            $this->display();
            return;
        }
        $t = json_decode($d['content']);
        if ($d['state_order'] == 2) {
            $list['state'] = "配送中";
        } else {
            $list['state'] = "已签收";
        }
        if ($d['type'] == 1) {
            //自己配送
            $list['source'] = "新华书店";
            $list['order_num'] = $order_id;
            $list['info'] = "您的订单已开始配送,快递员:{$t->name} {$t->phone}正在为您运送";
        } else {
            $list['source'] = $t->name;
            $list['order_num'] = $t->order_num;
            $list['info'] = "{$t->name}快递公司已揽件,单号:{$t->order_num}";
        }
        $list['record'] = [];
        //物流列表
        if ($d['type'] == 1) {
            //自己配送
            $data['info'] = "您的订单已开始配送,快递员:{$t->name} {$t->phone} 正在为您运送";
        } else {
            $data['info'] = "{$t->name}快递公司已揽件,单号:{$t->order_num}";
        }
        $data['time'] = $d['create_time'];
        array_push($list['record'], $data);
        $data['info'] = '您的订单开始处理';
        array_push($list['record'], $data);
        $data['info'] = '您的订单已出货';
        array_push($list['record'], $data);
        $this->assign("d", $list);
        $this->display();
    }

    //下单前检查-借阅检查
    function rentCheck(){
        $user_id = session("user_id");
        $is_ffree = I("post.is_ffree");
        $d=M('Card')->where(['user_id'=>$user_id])->find();
        if(!$d){
            $j=[
                'status'=>'error',
                'data'=>'会员卡不存在'
            ];
            echo json_encode($j);
            return;
        }
        $delay_time=json_decode($d['delay_time']);
        if($delay_time->start_time<time() && $delay_time->end_time >time()){
            $j=[
                'status'=>'error',
                'data'=>'冻结期间不可借阅'
            ];
            echo json_encode($j);
            return;
        }
        if(strtotime($d['expire_time'])<time()){
            $j=[
                'status'=>'error',
                'data'=>'会员有效期已过,请及时充值'
            ];
            echo json_encode($j);
            return;
        }
        if($is_ffree=='1' && $d['num_delivery']==0){
            $j=[
                'status'=>'error',
                'data'=>C('rent_freenum_name').'不足,请充值'
            ];
            echo json_encode($j);
            return;
        }
        //检查是否有未收货订单
        $where="user_id='$user_id' and state_order!='3' and state_order!='0' and type=1";
        $oc=M('Order_book')->where($where)->count();
        if($oc>0){
            $j=[
                'status'=>'error',
                'data'=>'您有未收货订单,请先确认订单'
            ];
            echo json_encode($j);
            return;
        }
        //检查库存
        $liststr = I("post.liststr");
        $list = bookinfo_strtoarr($liststr);
        $error=false;
        $error_message='';
        foreach($list as $k=>$v){
            //echo $v['book_id'].$v['num'];
            $map["book_id"]=$v['book_id'];
            $d=M('book')->where($map)->find();
            if(!$d){
                if($error){
                    $error_message.=','.$d['sm'];
                }else{
                    $error=true;
                    $error_message.='以下书不存在:'.$d['sm'];
                }
            }
            if ($d['stock_rent'] < $v['num']) {
                if($error){
                    $error_message.=','.$d['sm'];
                }else{
                    $error=true;
                    $error_message.='图书库存不足:'.$d['sm'];
                }
            }
        }
        if($error){
            $j=[
                'status'=>'error',
                'data'=>$error_message
            ];
            echo json_encode($j);
            return;
        }
        $j=[
            'status'=>'success',
            'data'=>'可借书'
        ];
        echo json_encode($j);
        return;
    }
    //点击借阅-检查是否会员
    function rentCheckVip(){
        $user_id = session("user_id");
        $d=M('Card')->where(['user_id'=>$user_id])->find();
        if(!$d){
            $j=[
                'status'=>'error',
                'code'=>'101',
                'data'=>'会员卡不存在'
            ];
            echo json_encode($j);
            return;
        }
        $delay_time=json_decode($d['delay_time']);
        if(!empty($delay_time) && strtotime($delay_time->start_time) < time() && strtotime($delay_time->end_time) > time()){
            $j=[
                'status'=>'error',
                'code'=>'102',
                'data'=>'冻结期间不可借阅'
            ];
            echo json_encode($j);
            return;
        }
        if(strtotime($d['expire_time'])<time()){
            $j=[
                'status'=>'error',
                'code'=>'103',
                'data'=>'非缴费会员或已过期,前往充值'
            ];
            echo json_encode($j);
            return;
        }

        $liststr = I("post.liststr");//要加入购物车的图书列表及数量
        $list = bookinfo_strtoarr($liststr);
        $sum = 0;
        foreach ($list as $v){
            $sum += $v["num"];
        }
        // 单次借阅数量为总可借阅数量的一半
        if ($sum > C("rentmax_wx") / 2) {
            $r = ["status" => "error" , "data" => "超出借书限制"];
            echo json_encode($r);
            return;
        }
        //判断是否超出借书限制
        //计算还有多少书未还
        $do = M("Order_book")->where(["user_id" => $user_id , "type" => 1 , "state_order" => 3])->field("order_id")->select();//取【该用户】状态为【已收货】的【借书】订单
        if (!$do) {//如果没有订单
            $c=0;
        }else{
            $m_order_id = [];//【订单号】数组初始化
            foreach ($do as $k => $v) {
                array_push($m_order_id , $v['order_id']);//把每条订单的订单号加入数组中
            }
            $map['order_id'] = ["in" , $m_order_id];    //订单号in
            $map['type'] = 1;                           //类型为借书
            $map['is_backed'] = 0;                      //状态为未归还
            $c = M("View_order_has_book")->where($map)->sum('quantity-num_backed-num_broken');    //查未归还书的条数
        }
        //判断未还的书加上本次要借的书，是否超出限制
        if($sum+$c > C("rentmax_wx")){
            $r = ["status" => "error" , "data" => "超出借书限制"];
            echo json_encode($r);
            return;
        }

        $j=[
            'status'=>'success',
            'data'=>'可借书'
        ];
        echo json_encode($j);
        return;
    }
}